import auth from '@/plugins/auth'
import router, { constantRoutes, dynamicRoutes } from '@/router'
import { getRouters } from '@/api/menu'
import Layout from '@/layout/index'
import ParentView from '@/components/ParentView'
import InnerLink from '@/layout/components/InnerLink'

// 路由 name 去重与外链路径规范化处理
const routeNameSet = new Set()
const routeNameCount = new Map()
const isExternal = (path) => /^(https?:)?\/\//i.test(path)
const b64 = (s) => {
  try { return btoa(unescape(encodeURIComponent(s))).replace(/=+$/, '') } catch (e) { return s.replace(/[^a-zA-Z0-9]/g, '') }
}
const uniqName = (name, path) => {
  if (!name) return undefined
  if (!routeNameSet.has(name)) { routeNameSet.add(name); return name }
  const keyBase = path || ''
  const safePath = keyBase.replace(/[^a-zA-Z0-9]/g, '_').slice(0, 40)
  let candidate = `${name}_${safePath}`
  if (!routeNameSet.has(candidate)) { routeNameSet.add(candidate); return candidate }
  candidate = `${name}_${b64(keyBase).slice(0, 16)}`
  if (!routeNameSet.has(candidate)) { routeNameSet.add(candidate); return candidate }
  // fallback: incremental suffix to ensure uniqueness even for完全相同 name+path
  const count = (routeNameCount.get(name) || 0) + 1
  routeNameCount.set(name, count)
  candidate = `${name}_${count}`
  routeNameSet.add(candidate)
  return candidate
}

const buildInnerLinkPath = (url) => '/inner/link/' + encodeURIComponent(url)

const permission = {
  state: {
    routes: [],
    addRoutes: [],
    defaultRoutes: [],
    topbarRouters: [],
    sidebarRouters: []
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes
      state.routes = constantRoutes.concat(routes)
    },
    SET_DEFAULT_ROUTES: (state, routes) => {
      state.defaultRoutes = constantRoutes.concat(routes)
    },
    SET_TOPBAR_ROUTES: (state, routes) => {
      state.topbarRouters = routes
    },
    SET_SIDEBAR_ROUTERS: (state, routes) => {
      state.sidebarRouters = routes
    },
  },
  actions: {
    // 生成路由
    GenerateRoutes({ commit }) {
      return new Promise(resolve => {
        // 向后端请求路由数据
        getRouters().then(res => {
          const sdata = JSON.parse(JSON.stringify(res.data))
          const rdata = JSON.parse(JSON.stringify(res.data))
          const sidebarRoutes = filterAsyncRouter(sdata)
          const rewriteRoutes = filterAsyncRouter(rdata, false, true)
          const asyncRoutes = filterDynamicRoutes(dynamicRoutes)
          rewriteRoutes.push({ path: '*', redirect: '/404', hidden: true })
          router.addRoutes(asyncRoutes)
          commit('SET_ROUTES', rewriteRoutes)
          commit('SET_SIDEBAR_ROUTERS', constantRoutes.concat(sidebarRoutes))
          commit('SET_DEFAULT_ROUTES', sidebarRoutes)
          commit('SET_TOPBAR_ROUTES', sidebarRoutes)
          resolve(rewriteRoutes)
        })
      })
    }
  }
}

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) {
  return asyncRouterMap.filter(route => {
    // 规范外链路径：必须以 http(s):// 开头的外链保持原样，内部路由必须以 / 开头
    if (route.path && !isExternal(route.path) && route.path[0] !== '/') {
      route.path = '/' + route.path
    }

    // 若后端返回外链但未指定 InnerLink 组件，主动转为可路由的 InnerLink
    if (route.path && isExternal(route.path) && route.component !== 'InnerLink') {
      route.meta = route.meta || {}
      route.meta.link = route.path
      // 使用安全的内部路由路径，避免包含 "://" 导致路由解析异常
      route.path = buildInnerLinkPath(route.path)
      route.component = 'InnerLink'
    }

    if (type && route.children) {
      route.children = filterChildren(route.children)
    }
    if (route.component) {
      // Layout ParentView 组件特殊处理
      if (route.component === 'Layout') {
        route.component = Layout
      } else if (route.component === 'ParentView') {
        route.component = ParentView
      } else if (route.component === 'InnerLink') {
        // 外链转内部可路由形式
        if (route.path && isExternal(route.path)) {
          route.meta = route.meta || {}
          route.meta.link = route.path
          route.path = buildInnerLinkPath(route.path)
        }
        route.component = InnerLink
      } else {
        route.component = loadView(route.component)
      }
    }
    // 去重/修正 name，避免 Duplicate named routes
    if (route.name) {
      route.name = uniqName(route.name, route.path || '')
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, route, type)
    } else {
      delete route['children']
      delete route['redirect']
    }
    return true
  })
}

function filterChildren(childrenMap, lastRouter = false) {
  var children = []
  childrenMap.forEach(el => {
    el.path = lastRouter ? lastRouter.path + '/' + el.path : el.path
    if (el.children && el.children.length && el.component === 'ParentView') {
      children = children.concat(filterChildren(el.children, el))
    } else {
      children.push(el)
    }
  })
  return children
}

// 动态路由遍历，验证是否具备权限
export function filterDynamicRoutes(routes) {
  const res = []
  routes.forEach(route => {
    if (route.permissions) {
      if (auth.hasPermiOr(route.permissions)) {
        res.push(route)
      }
    } else if (route.roles) {
      if (auth.hasRoleOr(route.roles)) {
        res.push(route)
      }
    }
  })
  return res
}

export const loadView = (view) => {
  if (process.env.NODE_ENV === 'development') {
    return (resolve) => require([`@/views/${view}`], resolve)
  } else {
    // 使用 import 实现生产环境的路由懒加载
    return () => import(`@/views/${view}`)
  }
}

export default permission
